package com.xuecheng.content.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.common.enums.content.CourseAuditEnum;
import com.xuecheng.content.entity.CourseBase;
import com.xuecheng.content.entity.CoursePub;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CoursePubService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Component
@RocketMQTransactionListener
@Slf4j
public class CoursePubTxMsgListener implements RocketMQLocalTransactionListener {

    @Autowired
    private CourseBaseService courseBaseService;

    @Autowired
    private CoursePubService coursePubService;


    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            //1.获得消息并解析
            Object payload = message.getPayload();
            Long courseBaseId = new Long(new String((byte[]) payload));
            //2.调用service层
            courseBaseService.saveCoursePubAndModifyAuditStatus(courseBaseId);

            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            log.error("事务监听器执行本地事务失败: {}", e.getMessage());
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    /*
     * 业务操作：
     *   1.判断课程基本信息的审核状态
     *   2.判断课程发布数据是否存在
     * */

    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        //获得消息并解析
        Object payload = message.getPayload();
        Long courseBaseId = new Long(new String((byte[]) payload));
        //1.判断课程基本信息的审核状态

        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        //此处抛出的异常是用于事务消息执行后的结果用（成功：Commit，失败：Rollback）
        if (!(CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode().equals(courseBase.getAuditStatus()))) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        //2.判断课程发布数据是否存在
        LambdaQueryWrapper<CoursePub> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CoursePub::getCourseId, courseBaseId);

        int count = coursePubService.count(queryWrapper);
        if (count < 1) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
